//
//  StatusPictureView.swift
//  SinaWebo
//
//  Created by mis on 16/3/21.
//  Copyright © 2016年 mis. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

private let PictureCellId = "PictureCellId"
private let PictureCellMargin: CGFloat = 5
class StatusPictureView: UICollectionView {
    
    var imageURLs: [NSURL]? {
        didSet {
            reloadData()
            let viewSize = self.calceViewSize()
            self.snp_updateConstraints { (make) -> Void in
                make.width.equalTo(viewSize.width)
                make.height.equalTo(viewSize.height)
            }
        }
    }
    
    private func calceViewSize() -> CGSize {
        let colum: CGFloat = 3.000001
        let maxWidth = screenW - 2 * StatusCellMargin
        
        let itemWidth = (maxWidth - 2 * PictureCellMargin) / colum
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        let imageCount = imageURLs?.count ?? 0
        
        if imageCount == 0 {
            return CGSizeZero
        }
        
        // 图片多大 布局就多大
        if imageCount == 1 {
            let key = imageURLs?.last?.absoluteString
            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key!)
            let w = image.size.width
            let h = image.size.height
            let imageSize = CGSize(width: w * 8, height: h * 8)
            layout.itemSize = imageSize
            return imageSize
        }
        
        
        if imageCount == 4 {
            let w = itemWidth * 2 + PictureCellMargin
            return CGSizeMake(w, w)
        }
        
        /*
            1 2 3 -- 1
            4 5 6 -- 2
            7 8 9 -- 3
        */
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let w = maxWidth
        let h = (row - 1) * PictureCellMargin + row * itemWidth
        return CGSizeMake(w, h)
    }
    
    init() {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = PictureCellMargin
        layout.minimumLineSpacing = PictureCellMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        registerClass(PictureCell.self, forCellWithReuseIdentifier: PictureCellId)
        dataSource = self
        self.backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension StatusPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! PictureCell
        cell.url = imageURLs![indexPath.item]
        return cell
    }
}


class PictureCell: UICollectionViewCell {
    var url: NSURL? {
        didSet {
            imageView.sd_setImageWithURL(url, placeholderImage: nil)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(imageView)
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true // 裁剪图片
        return imageView
    }()
}
